<template>
  <div class="cart-container">
    <!-- 返回上一级按钮 -->
    <el-button type="text" @click="goBack" style="font-size:18px; margin-bottom: 10px;">
      <el-icon style="vertical-align: middle;"><ArrowLeft /></el-icon>
      返回
    </el-button>
    <el-card>
      <!-- 头部全选 -->
      <div class="cart-header">
        <el-checkbox v-model="allChecked" @change="toggleAll">全选</el-checkbox>
      </div>
      <!-- 商品列表 -->
      <div v-if="cartList.length > 0">
        <div v-for="item in cartList" :key="item.itemId" class="cart-item">
          <el-checkbox v-model="item.selected" @change="() => toggleItem(item.itemId, item.selected)" />
          <img :src="item.productImage" class="cart-img" @click="goDetail(item.productId)" />
          <div class="cart-info">
            <div class="cart-title" @click="goDetail(item.productId)">{{ item.productName }}</div>
          </div>
          <div class="cart-price">￥{{ item.price }}</div>
          <div class="cart-qty">
            <el-button @click="changeQty(item, item.quantity - 1)" :disabled="item.quantity <= 1" size="small">-</el-button>
            <el-input-number v-model="item.quantity" :min="1" @change="val => changeQty(item, val)" size="small" />
            <el-button @click="changeQty(item, item.quantity + 1)" size="small">+</el-button>
          </div>
          <div class="cart-subtotal">￥{{ item.subtotal }}</div>
          <el-button type="danger" @click="remove(item.itemId)" size="small">删除</el-button>
        </div>
      </div>
      <div v-else class="cart-empty">购物车空空如也，快去选购商品吧！</div>
      <!-- 底部操作栏 -->
      <div class="cart-footer">
        <el-button @click="batchRemove" :disabled="selectedItems.length === 0">批量删除</el-button>
        <el-button @click="clearCart" :disabled="cartList.length === 0">清空购物车</el-button>
        <span style="flex:1"></span>
        <span>合计 <span class="cart-total">￥{{ totalPrice }}</span></span>
        <el-button type="primary" @click="showCheckout = true" :disabled="!cartList.length">去结算</el-button>
      </div>
    </el-card>

    <el-dialog v-model="showCheckout" title="确认订单" width="600px">
      <div v-if="addressList.length">
        <div style="margin-bottom: 12px;">
          <b>选择收货地址：</b>
          <el-select v-model="selectedAddressId" placeholder="请选择收货地址" style="width: 300px;">
            <el-option
              v-for="addr in addressList"
              :key="addr.addressId"
              :label="`${addr.receiverName} ${addr.phone} ${addr.province}${addr.city}${addr.district}${addr.detailAddress}`"
              :value="addr.addressId"
            />
          </el-select>
        </div>
        <el-form-item label="备注" style="margin-top: 12px;">
          <el-input v-model="orderRemark" placeholder="选填，给卖家的留言" maxlength="100" />
        </el-form-item>
        <el-table :data="cartList" style="width: 100%; margin-bottom: 12px;">
          <el-table-column prop="productName" label="商品名称" />
          <el-table-column prop="price" label="单价" width="100">
            <template #default="scope">
              ￥{{ scope.row.price.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="80" />
          <el-table-column label="小计" width="100">
            <template #default="scope">
              ￥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align: right; font-size: 16px; font-weight: bold;">
          总金额：<span style="color: #F56C6C;">￥{{ totalAmount.toFixed(2) }}</span>
        </div>
      </div>
      <div v-else style="color: #bbb;">请先添加收货地址</div>
      <template #footer>
        <el-button @click="showCheckout = false">取消</el-button>
        <el-button type="primary" @click="submitOrder" :disabled="!selectedAddressId || !cartList.length">提交订单</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, computed, ref } from 'vue'
import { useCartStore } from '@/stores/cartStore'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { getUserAddresses } from '@/utils/request'
import request from '@/utils/request'
import { ArrowLeft } from '@element-plus/icons-vue'

const cartStore = useCartStore()
const router = useRouter()
const showCheckout = ref(false)
const addressList = ref([])
const selectedAddressId = ref(null)
const orderRemark = ref('')

onMounted(() => {
  cartStore.fetchCart()
  fetchAddresses()
})

const cartList = computed(() => cartStore.cartList)
const selectedItems = computed(() => cartStore.selectedItems)
const totalPrice = computed(() => cartStore.totalPrice)
const allChecked = computed({
  get: () => cartStore.allChecked,
  set: (val) => cartStore.toggleAll(val)
})

function toggleAll(val) {
  cartStore.toggleAll(val)
}
function toggleItem(itemId, checked) {
  cartStore.toggleItem(itemId, checked)
}
function changeQty(item, val) {
  if (val < 1) return
  cartStore.updateCart(item.itemId, val, item.selected)
}
function remove(itemId) {
  ElMessageBox.confirm('确定要删除该商品吗？', '提示', { type: 'warning' })
    .then(() => cartStore.removeItem(itemId))
    .then(() => ElMessage.success('删除成功'))
}
function batchRemove() {
  if (selectedItems.value.length === 0) return
  ElMessageBox.confirm('确定要批量删除选中商品吗？', '提示', { type: 'warning' })
    .then(() => cartStore.batchRemove(selectedItems.value.map(i => i.itemId)))
    .then(() => ElMessage.success('批量删除成功'))
}
function clearCart() {
  ElMessageBox.confirm('确定要清空购物车吗？', '提示', { type: 'warning' })
    .then(() => cartStore.clear())
    .then(() => ElMessage.success('购物车已清空'))
}
function checkout() {
  if (selectedItems.value.length === 0) return
  ElMessageBox.confirm('确定要结算选中商品吗？', '结算', { type: 'info' })
    .then(() => cartStore.checkout(selectedItems.value.map(i => i.itemId)))
    .then(() => ElMessage.success('结算成功'))
}
function goDetail(productId) {
  router.push(`/products/${productId}`)
}

function fetchAddresses() {
  getUserAddresses().then(res => {
    if (res.success) {
      addressList.value = res.data || []
      if (addressList.value.length) {
        selectedAddressId.value = addressList.value.find(a => a.isDefault === 1)?.addressId || addressList.value[0].addressId
      }
    }
  })
}

function submitOrder() {
  if (!selectedAddressId.value) {
    ElMessage.error('请选择收货地址')
    return
  }
  const items = cartList.value.map(item => ({
    productId: item.productId,
    productName: item.productName,
    productPrice: item.price,
    quantity: item.quantity
  }))
  request.post('/api/order/create', {
    addressId: selectedAddressId.value,
    items,
    remark: orderRemark.value
  }).then(res => {
    if (res.success && res.data) {
      ElMessage.success('下单成功！')
      showCheckout.value = false
      router.push(`/profile/orders/${res.data.orderId}`)
    } else {
      ElMessage.error(res.message || '下单失败')
    }
  }).catch(e => {
    ElMessage.error(e.response?.data?.message || '下单失败')
  })
}

const totalAmount = computed(() =>
  cartList.value.reduce((sum, item) => sum + item.price * item.quantity, 0)
)

const goBack = () => {
  router.back()
}
</script>

<style scoped>
.cart-container {
  width: 900px;
  margin: 40px auto;
}
.cart-item {
  display: flex;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}
.cart-img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  margin: 0 16px;
  cursor: pointer;
}
.cart-info {
  flex: 1;
}
.cart-title {
  font-weight: bold;
  cursor: pointer;
}
.cart-price, .cart-subtotal {
  color: #e4393c;
  width: 100px;
  text-align: center;
}
.cart-qty {
  display: flex;
  align-items: center;
  width: 140px;
  justify-content: center;
}
.cart-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 16px 0;
  gap: 24px;
}
.cart-total {
  color: #e4393c;
  font-size: 18px;
  font-weight: bold;
}
.cart-empty {
  text-align: center;
  color: #888;
  padding: 40px 0;
  font-size: 18px;
}
</style>
